package com.chooseCourses.servlet.admin;

import com.chooseCourses.dao.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;

@WebServlet("/TeacherAdd")
public class TeacherAdd extends HttpServlet {
    public TeacherAdd() {
        super();
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Served at: ").append(req.getContextPath());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从jsp页面取值
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String age = req.getParameter("age");
        String technical = req.getParameter("technical");
        String loginid = req.getParameter("loginid");
        String loginpassword = req.getParameter("loginpassword");
        String userName = req.getParameter("userName");
        int userId = Integer.parseInt(req.getParameter("userId"));

        // 创建数据库操作对象
        BaseDao baseDao = new BaseDao();
        PreparedStatement ps = null;// 创建ps对象
        String sql = "insert into teacher(id,name,sex,age,technical,loginid,loginpassword) values(?,?,?,?,?,?,?)";

        // 调用db中的方法
        // 添加数据
        try {
            ps = baseDao.getConnection().prepareStatement(sql);
            ps.setString(1, id);
            ps.setString(2, name);
            ps.setString(3, sex);
            ps.setString(4, age);
            ps.setString(5, technical);
            ps.setString(6, loginid);
            ps.setString(7, loginpassword);
            ps.executeUpdate();// 执行sql语句
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try{
            baseDao.closeResource(null,ps,null);// 关闭数据流
        } catch (Exception e) {
            e.printStackTrace();
        }
        PrintWriter out = resp.getWriter();
        resp.sendRedirect("admin/teacherMes.jsp?userName=" + userName + "&userId=" + userId);
        doGet(req, resp);

    }



}
